<?php
declare (strict_types = 1);

namespace app\middleware;

use app\helpers\jwt_token;
use app\model\Admin;
use app\model\AuthRule;
use think\facade\Request;

class AuthCheck
{
    /**
     * @param $request
     * @param \Closure $next
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 16:42
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 中间件验证
     */
    public function handle($request, \Closure $next)
    {
        $header = Request::instance()->header();
        if (!array_key_exists('authorization', $header)) {
            return json([
                'code' => 1002,
                'data' => ['message' => 'Token不存在,拒绝访问']
            ]);
        }
        if (empty($header['authorization'])) {
            return json([
                'code' => 1002,
                'data' => ['message' => 'Token为空,拒绝访问']
            ]);
        }
        $token = $header['authorization'];
        $jwt = new jwt_token();
        $res = $jwt->checkTokenJWT($token);
        if ($res['code'] === 10000) {

            $admin = Admin::find($res['uid']);

            $request->uid = $res['uid'];
            $request->username = $admin['username'];
            // 检查用户权限
            $role_ids = array_column($admin->roles()->select()->toArray(),
                'rules');//获取该用户所属角色rules
            if (in_array('*', $role_ids)) {
                return $next($request);
            }

            $url = [];
            $res = AuthRule::where('id', 'in', implode(',', $role_ids))
                ->select()->toArray();

            foreach ($res as $key => $v) {
                $url[] = $v['name'];
            }

            $get_rule = $request->rule()->getRule(); //获取当前路由
            $get_rule = explode('/<',$get_rule);
            if (in_array(array_shift($get_rule), $url)) {
                return $next($request);
            }

            return json([
                'code' => 403,
                'data' => ['message' => '无权限, 请联系管理员申请']
            ]);
        }
        return json($jwt);
    }
}
